package com.task.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.task.bean.*;
import com.task.mapper.RankMapper;
import com.task.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: task_admin
 * @Author: LiuZhe
 */
@Slf4j
@Configuration
public class GenerateRankTask {

    @Autowired
    private RankMapper rankMapper;

    @Autowired
    private IStudentService studentService;

    // 有成绩 score stu_id
    @Autowired
    private IEvaluateService evaluateService;

    @Autowired

    @Scheduled(cron = "0 0 * * * ?")
    public void execute() {
        List<Evaluate> evaluateList = evaluateService.list();
       // 组装名字加成绩 成绩是多个
        List<Student> studentList = studentService.list();
        studentList.forEach(stuItem -> {
            List<Evaluate> evaluateStuList = evaluateService.queryEvaluateByStuId(stuItem.getId());
            BigDecimal sum = new BigDecimal(0.00);
            for (Evaluate evaluate: evaluateStuList) {
                sum = sum.add(new BigDecimal(evaluate.getScore()));
            }
            List<Rank> selectList = rankMapper.queryByStuId(stuItem.getId());
            if (ObjectUtils.isEmpty(selectList)) {
                Rank rank = new Rank();
                rank.setRank(sum.doubleValue());
                rank.setStuId(stuItem.getId());
                rank.setName(stuItem.getName());
                rankMapper.insertNew(rank);
            } else {
                rankMapper.updateByStuId(stuItem.getId(), sum.doubleValue());
            }
        });
    }
}
